package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
)

// casbin 表

type CasbinRule struct {
	PType string `json:"p_type"`
	V0    string `json:"v0"`
	V1    string `json:"v1"`
	V2    string `json:"v2"`
	V3    string `json:"v3"`
	V4    string `json:"v4"`
	V5    string `json:"v5"`
}

// 重置表名
func (c *CasbinRule) TableName() string {
	return "casbin_rule"
}

// 批量插入casbin表
func (c *CasbinRule) Create(db *gorm.DB, pType, roleKey string, menus []*Menu) error {
	if len(menus) == 0 {
		return nil
	}
	sqlStr := "INSERT INTO casbin_rule (p_type, v0, v1, v2, v3, v4, v5) VALUES "
	for i := 0; i < len(menus); i++ {
		sqlStr += fmt.Sprintf("('%s', '%s', '%s', '%s', '%s', '%s', '%s'),", pType, roleKey, menus[i].Path, menus[i].Action, "", "", "")
	}
	sqlStr = sqlStr[0:(len(sqlStr) - 1)]
	return db.Exec(sqlStr).Error
}

// 根据角色删除
func (c *CasbinRule) DeleteCasbin(db *gorm.DB, pType, roleKey string) error {
	return db.Where("p_type = ?", pType).Where("v0 = ?", roleKey).Delete(&c).Error
}

// 根据用户和角色添加
func (c *CasbinRule) CreateCasbinUserRole(db *gorm.DB, pType, username string, roles []*Role) error {
	if len(roles) == 0 {
		return nil
	}
	sqlStr := "INSERT INTO casbin_rule (p_type, v0, v1, v2, v3, v4, v5) VALUES "
	for i := 0; i < len(roles); i++ {
		sqlStr += fmt.Sprintf("('%s', '%s', '%s', '%s', '%s', '%s', '%s'),", pType, username, roles[i].RoleKey, "", "", "", "")
	}
	sqlStr = sqlStr[0:(len(sqlStr) - 1)]
	return db.Exec(sqlStr).Error
}

// 根据用户和类型删除
func (c *CasbinRule) DeleteCasbinUserRole(db *gorm.DB, pType, username string) error {
	return db.Where("p_type = ?", pType).Where("v0 = ?", username).Delete(&c).Error
}
